﻿using Microsoft.VisualStudio.DebuggerVisualizers;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Text;

namespace FR.CodeVisualizer.ObjectSource
{
    public class SqlConnectionVisualizerObjectSource : VisualizerObjectSource
    {
        public override void GetData(object target, System.IO.Stream outgoingData)
        {
            SQLQueryOptions options = new SQLQueryOptions();

            try
            {
                if (target is OleDbCommand)
                {
                    OleDbCommand command = target as OleDbCommand;

                    if (command.Connection != null)
                        options.ConnectionString = command.Connection.ConnectionString;

                    StringBuilder sb = new StringBuilder();
                    foreach (OleDbParameter parameter in command.Parameters)
                    {
                        sb.AppendLine(string.Format("DECLARE {0} {1};", parameter.ParameterName, parameter.OleDbType));
                        sb.AppendLine(string.Format("SET {0} = '{1}';", parameter.ParameterName, parameter.Value));
                    }

                    sb.AppendLine();
                    sb.AppendLine(command.CommandText);

                    options.SQLCommand = sb.ToString();
                    options.IsQuery = true;
                }
                else if (target is SqlCommand)
                {
                    SqlCommand command = target as SqlCommand;

                    if (command.Connection != null)
                        options.ConnectionString = command.Connection.ConnectionString;

                    StringBuilder sb = new StringBuilder();
                    foreach (SqlParameter parameter in command.Parameters)
                    {
                        sb.AppendLine(string.Format("DECLARE {0} {1};", parameter.ParameterName, parameter.SqlDbType));
                        sb.AppendLine(string.Format("SET {0} = '{1}';", parameter.ParameterName, parameter.Value));
                    }

                    sb.AppendLine();
                    sb.AppendLine(command.CommandText);

                    options.SQLCommand = sb.ToString();
                    options.IsQuery = true;
                }
            }
            catch (System.Exception ex)
            {
                options.SetExceptionMessage(ex);
            }

            StreamSerializer.ObjectToStream(outgoingData, options);
        }

        public override void TransferData(object target, System.IO.Stream incomingData, System.IO.Stream outgoingData)
        {
            base.TransferData(target, incomingData, outgoingData);
        }
    }
}
